package com.xiaoyushu.xiaoyushu.auth.filter;

import com.xiaoyushu.framework.common.constant.GlobalConstants;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @description: 提取请求头中的用户 ID 保存到上下文中，以方便后续使用
 * @author: xiaoyushu
 * @date: 2022/5/27 10:05 下午
 */
@Component
@Slf4j
public class HeaderUserId2ContextFilter extends OncePerRequestFilter {
    /**
     * Same contract as for {@code doFilter}, but guaranteed to be
     * just invoked once per request within a single request thread.
     * See {@link #shouldNotFilterAsyncDispatch()} for details.
     * <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
     * default ServletRequest and ServletResponse ones.
     *
     * @param request
     * @param response
     * @param filterChain
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //从请求头中获取用户ID
        String userId=request.getHeader(GlobalConstants.USER_ID);

        log.info("## HeaderUserId2ContextFilter,用户Id:{}",userId);

        //判断请求头中是否存在用户ID
        if(StringUtils.isBlank(userId)){
            //若唯恐直接放行
            filterChain.doFilter(request,response);
            return;
        }
        //如果 header 中存在userID,则设置到ThreadLocal中
        log.info("====设置 userId 到ThreadLocal 中，用户ID：{}",userId);

        LoginUserContextHolder.setUserId(userId);

        try {
            //将请求和响应传递给过滤链中的下一个过滤器
            filterChain.doFilter(request, response);//: 将请求和响应传递给过滤链中的下一个过滤器。如果没有下一个过滤器，则请求会到达控制器。
        } finally {
            //一定要删除ThreadLocal中的 防止内存泄露
            LoginUserContextHolder.remove();
            log.info("====删除 userId from ThreadLocal 中，用户ID：{}", userId);
        }


    }
}
